#ifndef ________MOTOR_HALL_H________
#define ________MOTOR_HALL_H________

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

#include "stm32f1xx_hal.h"
#include "motor_foc.h"
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "bidirectional_filter.h"

#define HALL_FILTER_WINDOW_SIZE 5

// 霍尔传感器状态枚举
typedef enum {
    HALL_STATE_000 = 0,
    HALL_STATE_001 = 1,
    HALL_STATE_010 = 2,
    HALL_STATE_011 = 3,
    HALL_STATE_100 = 4,
    HALL_STATE_101 = 5,
    HALL_STATE_110 = 6,
    HALL_STATE_111 = 7
} HallState_e;

// 霍尔传感器配置结构体
typedef struct {
    GPIO_TypeDef* hall_a_port;
    uint16_t hall_a_pin;
    GPIO_TypeDef* hall_b_port;
    uint16_t hall_b_pin;
    GPIO_TypeDef* hall_c_port;
    uint16_t hall_c_pin;
} HallConfig_t;

// 霍尔传感器处理结构体
typedef struct {
    HallConfig_t config;
    uint8_t last_hall_state;
    uint8_t current_hall_state;
    int16_t electrical_angle;
    uint32_t last_update_time;
    uint8_t direction;  // 0: 未知, 1: 正转, 2: 反转
    uint16_t speed_rpm;
    uint32_t revolution_count;  // 转数计数
	uint8_t hall_a_history[HALL_FILTER_WINDOW_SIZE];
    uint8_t hall_b_history[HALL_FILTER_WINDOW_SIZE];
    uint8_t hall_c_history[HALL_FILTER_WINDOW_SIZE];
    uint8_t history_index; // 添加历史索引
} HallHandler_t;

// 函数声明
void HALL_Init(HallHandler_t* hall_handler, HallConfig_t* config);
uint8_t HALL_ReadHallSensors(HallHandler_t* hall_handler);
void HALL_Update(HallHandler_t* hall_handler);
int16_t HALL_GetElectricalAngle(HallHandler_t* hall_handler);
uint8_t HALL_GetDirection(HallHandler_t* hall_handler);
uint16_t HALL_GetSpeedRPM(HallHandler_t* hall_handler);
void HALL_UpdateFOCInputs(HallHandler_t* hall_handler, FOC_Type* foc_controller);




#ifdef __cplusplus
}
#endif // __cplusplus

#endif //________MOTOR_HALL_H________
